package com.qf.sl.youshare;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.*;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.qf.sl.youshare.db.DataManager;
import com.qf.sl.youshare.model.ProductCollect;
import com.qf.sl.youshare.model.UserLogin;
import com.qf.sl.youshare.utils.FileCache;
import com.qf.sl.youshare.utils.ImageCache;
import com.qf.sl.youshare.utils.ImageLoader;
import com.qf.sl.youshare.utils.UserCurrent;

/**
 * Created by IDEA
 * User : SL
 * on  2015/2/9.
 * 20:59
 */
public class CoreGoodsActivity extends Activity implements View.OnClickListener {

    private TextView coreNameView;
    private TextView coreBriefView;
    private ImageView coreIconView;
    private ImageView coreUpBgView;
    private TextView corePriceView;

    private String name;
    private String goodsBrief;
    private String price;
    private String goodsThumb;
    private String goodsId;
    private String type;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_core_goods);

        coreNameView = (TextView) findViewById(R.id.goods_core_name);
        coreBriefView = (TextView) findViewById(R.id.goods_core_brief);
        coreIconView = (ImageView) findViewById(R.id.goods_core_icon);
        coreUpBgView = (ImageView) findViewById(R.id.goods_core_up_bg);
        corePriceView = (TextView) findViewById(R.id.goods_core_price);
        Button buyBtn = (Button) findViewById(R.id.goods_core_buy);
        Button collectBtn = (Button) findViewById(R.id.goods_collect);

        collectBtn.setOnClickListener(this);
        buyBtn.setOnClickListener(this);

        Intent intent = getIntent();

        int upColor = initInterface(intent);

        ActionBar actionBar = getActionBar();

        initActionBar(upColor, actionBar);

    }

    /**
     * 提取代码，初始化ActionBar
     * @param upColor
     * @param actionBar
     */
    private void initActionBar(int upColor, ActionBar actionBar) {
        if (actionBar != null) {
            // 设置返回按钮
            actionBar.setDisplayHomeAsUpEnabled(true);

            // 去掉ActionBar上面的图标
            actionBar.setIcon(new ColorDrawable(Color.TRANSPARENT));

            // 标题居中
            actionBar.setDisplayShowCustomEnabled(true);

            // 从layout文件夹中加载布局，然后通过代码修改标题，
            // 实现一个标题 layout布局的共用.
            LayoutInflater inflater = LayoutInflater.from(this);

            View view = inflater.inflate(R.layout.actionbar_main_title, null);

            // 获取view中的 TextView，进行标题的设置

            TextView txtTitle = (TextView) view.findViewById(R.id.actionbar_title);
            if (txtTitle != null) {
                txtTitle.setText("商城");
            }

            actionBar.setCustomView(
                    view,
                    new ActionBar.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                            Gravity.CENTER
                    )
            );

            // 取消默认标题
            actionBar.setDisplayShowTitleEnabled(false);

            actionBar.setBackgroundDrawable(new ColorDrawable(upColor));
        }
    }

    /**
     * 提取代码，初始化界面上的数据
     * @param intent
     * @return
     */
    private int initInterface(Intent intent) {
        goodsId = intent.getStringExtra("goodsId");
        type = intent.getStringExtra("type");

        int upColor = intent.getIntExtra("upColor", R.color.white);
        coreUpBgView.setBackgroundColor(upColor);

        name = intent.getStringExtra("name");
        coreNameView.setText(name);

        goodsBrief = intent.getStringExtra("goodsBrief");
        coreBriefView.setText(goodsBrief);

        price = intent.getStringExtra("price");
        if (price != null) {
            corePriceView.setText(price);
        }

        goodsThumb = intent.getStringExtra("goodsThumb");
        if (goodsThumb != null && goodsThumb.length() > 0) {
            if (!goodsThumb.startsWith("http://") && !goodsThumb.startsWith("https://")) {
                goodsThumb = Constants.IMAGE_SERVER + goodsThumb;
            }
            //设置默认图片,避免出现复用的View显示以前图片的问题
            coreIconView.setImageResource(R.drawable.product_default);

            ImageCache imageCache = ImageCache.getInstance();
            Bitmap bitmap = imageCache.getImage(goodsThumb);

            if (bitmap != null) {

                coreIconView.setImageBitmap(bitmap);

            }else {
                //不包含缓存,就进行本地文件的加载

                //TODO 加载本地文件内容

                FileCache fileCache = FileCache.getInstance();
                byte[] bytes = fileCache.getFileContent(goodsThumb);
                if (bytes != null && bytes.length > 0) {
                    Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    coreIconView.setImageBitmap(bmp);

                    imageCache.putImage(goodsThumb,bmp);
                }else {

                    //进行网络的加载
                    // 1,开启异步任务

                    ImageLoader task = new ImageLoader(coreIconView);
                    task.execute(goodsThumb);
                }
            }
        }
        return upColor;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main,menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        Intent intent = null;
        switch (id){
            case R.id.goods_core_buy:
                intent = new Intent(this, CartActivity.class);
                break;
            case R.id.goods_collect:
                ProductCollect productCollect = new ProductCollect();

                productCollect.setName(name);
                productCollect.setPid(goodsId);
                productCollect.setDescription(goodsBrief);
                price = price.replace("￥", "");
                price = price.replace("元", "");
                productCollect.setPrice(Float.parseFloat(price));
                productCollect.setThumb(goodsThumb);
                productCollect.setType(type);

                UserCurrent userCurrent = UserCurrent.getInstance();

                //设置默认值为 0000，当当前没有账户登录时，设置的用户ID
                String userId  = Constants.DEFAULT_USER_ID;
                UserLogin userLogin = userCurrent.getUserLogin();
                if (userLogin != null) {
                    userId = userLogin.getUserId();
                }

                DataManager manager = DataManager.getInstance();

                int result = manager.productCollect(productCollect, userId);

                if (result == 1){
                    Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();
                    intent = new Intent(this, ProductCollectActivity.class);
                }else if (result == 2){
                    Toast.makeText(this, "已经收藏过", Toast.LENGTH_SHORT).show();
                    intent = new Intent(this, ProductCollectActivity.class);
                }else if (result == 3){
                    Toast.makeText(this, "数据库尚未开启", Toast.LENGTH_SHORT).show();
                }
                break;
        }
        startActivity(intent);
    }
}